// https://leetcode.cn/problems/sliding-window-maximum/submissions/

class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        vector<int> res;
        if (nums.empty() || nums.size() < k) return res;
        deque<int> q;
        for (int i = 0; i < nums.size(); ++i) {
            while (!q.empty() && nums[i] > nums[q.front()]) q.pop_front();
            q.push_front(i);
            if (!q.empty() && q.back() <= i - k) q.pop_back();
            if (i >= k - 1) res.push_back(nums[q.back()]);
        }
        return res;
    }
};